<template>
  <view class="container">
    <!-- 对话历史区域 -->
    <scroll-view class="chat-history" scroll-y="true" ref="scrollView">
      <view v-for="(message, index) in messages" :key="index" class="message-item">
        <view :class="['message', message.type === 'user' ? 'user' : 'ai']">
          {{ message.content }}
        </view>
      </view>
    </scroll-view>

    <!-- 输入框和发送按钮 -->
    <view class="input-area">
      <input
        v-model="inputText"
        type="text"
        placeholder="请输入消息"
        class="input"
      />
      <button @click="sendMessage" class="send-button">发送</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      inputText: "", // 用户输入的内容
      messages: [], // 对话历史
      API_KEY: "vb2U3ouOHabEqOITrkxkOSTn", // 替换为你的百度AI API Key
      SECRET_KEY: "ETp8KTjMg4Te5WE4nggVnBRKMXFopUe2", // 替换为你的百度AI Secret Key
      ACCESS_TOKEN: "", // 用于存储获取到的access_token
    };
  },
  methods: {
    async sendMessage() {
      if (!this.inputText.trim()) {
        uni.showToast({
          title: "请输入内容",
          icon: "none",
        });
        return;
      }

      // 添加用户消息到对话历史
      this.messages.push({
        type: "user",
        content: this.inputText,
      });

      // 滚动到最新消息
      this.$nextTick(() => {
        this.scrollToBottom();
      });

      // 获取access_token（如果尚未获取）
      if (!this.ACCESS_TOKEN) {
        await this.getAccessToken();
      }

      // 调用AI接口
      try {
        uni.showLoading({
          title: "正在加载",
        });

        const aiResponse = await this.callAI(this.inputText);

        // 添加AI的回复到对话历史
        this.messages.push({
          type: "ai",
          content: aiResponse,
        });

        // 滚动到最新消息
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } catch (error) {
        console.error("AI请求失败", error);
        uni.showToast({
          title: "消息发送失败",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }

      // 清空输入框
      this.inputText = "";
    },
    scrollToBottom() {
      this.$refs.scrollView.scrollTo({
        y: this.$refs.scrollView.scrollHeight,
        duration: 300,
      });
    },
    async getAccessToken() {
      const AUTH_URL = "https://aip.baidubce.com/oauth/2.0/token";
      const response = await uni.request({
        url: AUTH_URL,
        method: "POST",
        data: {
          grant_type: "client_credentials",
          client_id: this.API_KEY,
          client_secret: this.SECRET_KEY,
        },
      });

      if (response[1].statusCode === 200) {
        this.ACCESS_TOKEN = response[1].data.access_token;
      } else {
        uni.showToast({
          title: "获取access_token失败",
          icon: "none",
        });
        console.error("获取access_token失败", response[1].data);
      }
    },
    async callAI(userInput) {
      const API_URL = "https://qianfan.baidubce.com/v2/ai_search/chat/completions";

      return new Promise((resolve, reject) => {
        uni.request({
          url: `${API_URL}?access_token=${this.ACCESS_TOKEN}`,
          method: "POST",
          header: {
            "Content-Type": "application/json",
          },
          data: JSON.stringify({
            messages: [
              {
                role: "user",
                content: userInput,
              },
            ],
          }),
          success: (res) => {
            if (res.statusCode === 200) {
              const response = res.data.result || "抱歉，我没有理解你的问题。"; // 根据实际返回结构调整
              resolve(response);
            } else {
              reject(new Error("AI接口返回错误：" + res.data.error.message));
            }
          },
          fail: (err) => {
            reject(new Error("请求AI接口失败：" + err));
          },
        });
      });
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 10px;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

.message-item {
  margin-bottom: 10px;
}

.message {
  padding: 8px 12px;
  border-radius: 10px;
  max-width: 70%;
  word-wrap: break-word;
}

.message.user {
  background-color: #e1ffc4;
  align-self: flex-end;
}

.message.ai {
  background-color: #e1f0ff;
  align-self: flex-start;
}

.input-area {
  display: flex;
  justify-content: space-between;
  position: fixed; /* 固定在底部 */
  bottom: 0; /* 距离底部 0 */
  width: 98%; /* 宽度占满整个屏幕 */
  padding: 10px; /* 添加一些内边距 */
  background-color: white; /* 添加背景颜色，防止内容遮挡 */
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

.send-button {
  padding: 10px 20px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 5px;
}
</style>